from RaspiCode.MQTTCommOOP import MyMqttClient
from multiprocessing import Process, Queue
from RaspiCode.mysqlUtils import PdbcUtil
import time
import numpy as np
from RaspiCode.Filter import filter, filterUtils
from RaspiCode.requestFromCloud import requestFromServer
import matplotlib.pyplot as plt


class MainDataProcessor():
    def __init__(self):
        # self.mqttClient = MyMqttClient()
        # self.pdbcUtils = PdbcUtil()
        # self.queue = Queue()
        # self.mqttClient.queue = self.queue
        self.rhFilterQueue = []
        self.co2FilterQueue = []
        self.tvocFilterQueue = []
        self.lightFilterQueue=[]
        self.lastSentTime = time.time()

    # def getCommand(self, cmd: str):

    def sendCommand(self, cmd: str):

        f = self.mqttClient.publish('control', cmd, 1)
        if (self.mqttClient._inflight_messages > 0):  # 我也不知道这个库为什么会犯这个毛病，总之似乎不太对劲……
            self.mqttClient._inflight_messages -= 1

        self.lastSentTime = time.time()

    def controlProcess(self):
        while (1):
            time.sleep(0.1)
            cmd = requestFromServer('117.73.9.242')

            if (cmd == None):  # 没有任何任务的话就继续
                continue
            else:

                angle = cmd['motion'][0]
                self.sendCommand("<%s>" % angle)

    def test(self):
        f = open('log.csv')
        rows = f.readlines()
        l0 = []
        l1 = []
        for row in rows:
            l = row.strip().split(',')
            temp = float(l[0])
            rh = float(l[1])
            light = float(l[2])

            l1.append(light)
            rh, self.rhFilterQueue = filterUtils(rh, self.rhFilterQueue, r=2 * 10 ** -3, q=8 * 10 ** -5)
            light, self.lightFilterQueue = filterUtils(light, self.lightFilterQueue, r= 10 ** -4.2, q=10 ** -5.2)
            print(self.lightFilterQueue)
            l0.append(light)
        plt.plot(np.linspace(0,100,100),l0[:100], 'r')
        plt.plot(np.linspace(0,100,100),l1[:100], 'g')
        plt.show()

    def continousFiltering(self, row):


        temp = rh = light = 0.0

        l = row.strip().split(',')
        temp = float(l[0])
        rh = float(l[1])
        light = float(l[2])

        rh, self.rhFilterQueue = filterUtils(rh, self.rhFilterQueue, r=2 * 10 ** -3, q=8 * 10 ** -5)
        light, self.lightFilterQueue = filterUtils(light, self.lightFilterQueue, r=10 ** -4.2, q=10 ** -5.2)

        return temp, rh, light
        # plt.plot(l0, 'r')
        # plt.plot(l1, 'g')
        # plt.show()

    def dataProcess(self):
        while (1):
            if (self.queue.empty()):
                time.sleep(0.1)
                pass
            else:
                elem = self.queue.get()

                # 温度测得比较准，几乎不需要卡尔曼滤波，所以就不动了。
                rh, self.rhFilterQueue = filterUtils(elem[2], self.rhFilterQueue, r=10 ** -3, q=10 ** -5)
                co2, self.co2FilterQueue = filterUtils(elem[3], self.co2FilterQueue, r=10 ** -3.4, q=10 ** -4.7)
                tvoc, self.tvocFilterQueue = filterUtils(elem[4], self.tvocFilterQueue, r=10 ** -3.4, q=10 ** -4.85)
                print("sssssss", elem)
                print(elem[2], rh)
                print(elem[3], co2)
                print(elem[4], tvoc)
                self.pdbcUtils.insertRHAndTempData(t=elem[0], temp=elem[1], RH=rh, CO2=co2, TVOC=elem[4])


if __name__ == "__main__":
    dp = MainDataProcessor()
    dp.test()
    # proc = Process(target=dp.dataProcess, args=())  # 使用了一个新的进程进行队列的计算。
    # # 这里使用了可并行的架构。稍加改进，多机并行也是可以的。
    # proc.start()
    #
    # controlProcess = Process(target=dp.controlProcess, args=())
    # controlProcess.start()
    #
    # dp.mqttClient.loop_forever()
